import logging

from flask import request

from plugins_v3._login.login import login
from utils.decorators.cache import cache
from utils.decorators.check_sign import check_sign
from utils.decorators.guest import guest
from utils.decorators.request_limit import request_limit
from utils.session import session
from . import api, config


@api.route('/grade', methods=['GET'])
@check_sign({'name', 'passwd'})
@request_limit()
@cache({'name'}, 180)
@guest('guest')
def handle_grade():
    name = request.args.get('name', type=str)
    passwd = request.args.get('passwd', type=str)
    cookies = login(name, passwd)
    post_data = {
        'xnm': '',
        'xqm': '',
        'queryModel.showCount': 1000,
        '_search': 'false'
    }
    try:
        grade = session.post(config.grade_url, post_data, cookies=cookies).json()
    except Exception:
        cookies = login(name, passwd, True)
        grade = session.post(config.grade_url, post_data, cookies=cookies).json()
        logging.warning("捕获成绩查询异常!")
    grade_items = {}
    for item in grade['items']:
        dict_key = int(item['xnmmc'][:4]) + int(item['xqmmc'])/2
        if dict_key not in grade_items:
            grade_items[dict_key] = []
        grade_items[dict_key].append({
            'name': item.get('kcmc', '')+'['+item.get('kcxzmc', '')+']',
            'credit': float(item['xf']) if 'xf' in item else '',
            'grade': item.get('bfzcj', ''),
            'gradePoint': float(item['jd']) if 'jd' in item else '',
            'testType': item.get('kcxzmc', ''),
            'testStatus': item.get('ksxz', ''),
        })
    index = sorted(grade_items.keys())
    data = []
    for list_index in index:
        data.append(grade_items[list_index])
    g_a, g_b = 0, 0
    g_a_, g_b_ = 0, 0
    for item_i in data:
        a, b = 0, 0
        a_, b_ = 0, 0
        for item_j in item_i:
            if item_j['credit'] and item_j['gradePoint']:
                t = item_j['credit'] * item_j['gradePoint']
                a += t
                g_a += t
                b += item_j['credit']
                g_b += item_j['credit']
                if item_j['testType'] in ['必修']:
                    a_ += t
                    g_a_ += t
                    b_ += item_j['credit']
                    g_b_ += item_j['credit']
                del item_j['testType']
                del item_j['testStatus']
        if b:
            item_i.append({
                'name': '学期平均绩点',
                'gradePoint': round(a / b, 2)
            })
        if b_:
            item_i.append({
                'name': '学期平均绩点（必修）',
                'gradePoint': round(a_ / b_, 2)
            })
    if g_b:
        data[-1].append({
            'name': '总平均绩点',
            'gradePoint': round(g_a / g_b, 2)
        })
    if g_b_:
        data[-1].append({
            'name': '总平均绩点（必修）',
            'gradePoint': round(g_a_ / g_b_, 2)
        })
    return {
        'code': 0,
        'data': data
    }

